﻿using System.Data;
using Mammoth.Entities;
using Mammoth.Services;
using NHibernate;
using NHibernate.ByteCode.Castle;
using NHibernate.Cfg;
using NHibernate.Cfg.Loquacious;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
using NHibernate.Tool.hbm2ddl;


namespace Mammoth.Repositories
{
    public class DataSessionFactory : IDataSessionFactory
    {
        ISessionFactory SessionFactory;

        private void ConfigureDatabase(IDbIntegrationConfigurationProperties db, 
            IDatabaseConfiguration config)
        {
            db.Dialect<MySQLDialect>();
            db.Driver<MySqlDataDriver>();
            db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            db.IsolationLevel = IsolationLevel.ReadCommitted;
            db.ConnectionString = config.ConnectionString;
            db.Timeout = 10;

            // enabled for testing
            db.LogSqlInConsole = true;
            db.AutoCommentSql = true;
        }

        /// <summary>
        /// Configure NHibernate and update database schema. expensive call
        /// </summary>
        public void Configure(IDatabaseConfiguration configSection)
        {
            var config = new Configuration();
            config.Proxy(p => p.ProxyFactoryFactory<ProxyFactoryFactory>());
            config.SessionFactoryName("Silicon.SessionFactory");
            config.DataBaseIntegration(x => ConfigureDatabase(x, configSection));
            
            var mapper = new ModelMapper();
            var mappings = typeof(Entity).Assembly.GetTypes();
            mapper.AddMappings(mappings);
            var domainMap = mapper.CompileMappingForAllExplicitlyAddedEntities();
            config.AddMapping(domainMap);

            new SchemaUpdate(config).Execute(false, true);

            SessionFactory = config.BuildSessionFactory();
        }


        public IStatelessSession GetSession()
        {
            return SessionFactory.OpenStatelessSession();
        }
    }
}
